﻿using Spring.Context;
using Spring.Context.Support;
using Spring.Data.NHibernate;
using Spring.Data.Common;
using Commons.TypeUtil;

namespace DataVisit.Factory
{
    /// <summary>
    /// 这个类提供一个全局的对象容器并自身也提供了返回对象的方法.
    /// <br />
    /// 全局对象的配置文件默认是Application-context.xml
    /// </summary>
    public class ApplicationFactory
    {
        protected static IApplicationContext _context;

        private ApplicationFactory()
        {
           // LocalSessionFactoryObject o = new LocalSessionFactoryObject();
        }

        /// <summary>
        /// 返回一个对象容器
        /// </summary>
        public static IApplicationContext Context
        {
            get 
            {
                Init();
                return _context;
            }
        }

        public static void Init()
        {
            if (_context == null)
            {
                //string [] k = new string[] { @"assembly://ProjectData/ProjectData/Config.Application-context.xml" };
                _context = new XmlApplicationContext(new string[] { @"assembly://DataVisit/DataVisit/Config.Application-context.xml" });
                //SqlConnectionProvider.ConnStr = provider.ConnectionString;
            }
        }

        /// <summary>
        /// 利用范型从对象容器中返回一个命名好的对象
        /// </summary>
        /// <param name="objectName"></param>
        /// <returns></returns>
        public static T GetTypedObject<T>(string objectName)
        {
            return (T)Context.GetObject(objectName, typeof(T));
        }
        /// <summary>
        /// 从对象容器中返回一个命名好的基本对象
        /// </summary>
        /// <param name="objectName"></param>
        /// <returns></returns>
        public static object GetObject(string objectName)
        {
            return Context.GetObject(objectName);
        }

        /// <summary>
        /// Gets the string converter.
        /// </summary>
        /// <returns></returns>
        public static StringValueConverter GetStringConverter()
        {
            return (StringValueConverter)GetObject("strConverter");
        }
    }
}
